# -*- coding: utf-8 -*-
# __author__ = 'yeslf'
# env: python 2.7 docker  4.4.4
# fuction: 按镜像标签名称清理镜像 

import docker

def getimgtags(imgname):

  client = docker.from_env()


  # 获取当前环境下对应镜像的tag
  #getimgs=client.images.list("okbusybox")
  getimgs=client.images.list(imgname,all=True)

  #返回对应镜像 tag 列表
  devtaglist=[]
  testtaglist=[]
  mastertaglist=[]
  releasetaglist=[]


  #get all tags
  imgtags=getimgs[0].tags


  for i in imgtags:

    getimgtag=i.split(":")[1]

    # imgbranch
    if getimgtag.find("dev")==0:

       devtaglist.append(getimgtag)


    # imgbranch
    if getimgtag.find("test")==0:

       testtaglist.append(getimgtag)

    # imgbranch
    if getimgtag.find("master")==0:

       mastertaglist.append(getimgtag)


    # imgbranch
    if getimgtag.find("release")==0:

       releasetaglist.append(getimgtag)


  usetaglist=(devtaglist,testtaglist,mastertaglist,releasetaglist)

  return usetaglist


# 按 tag 清理不用镜像
def delimg(imgname,taglist):

  client = docker.from_env()

  taglist.sort()
  taglistlen=len(taglist)

  if taglistlen>6:


    #清理多余的 镜像
    for x in range(taglistlen - 6):

      deluse=imgname+taglist[x]

      try:
        client.images.get(deluse)  
      except Error:
        print("not found img  %s " %deluse )

      else:
        client.images.remove(deluse)
        
        print(" %s img  clear  running " % deluse)


# 执行清理

getdeltaglist=getimgtags("bash")

for x in getdeltaglist:
    print("获取到 镜像 标签列表")
    print(x)
    delimg("bash:",x)



